package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisIdWorder;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorder redisIdWorder;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisIdWorder redisIdWorker;

    private BlockingQueue<VoucherOrder> blockingQueue = new ArrayBlockingQueue<>(1024*1024);
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    // 提前读取脚本 静态代码块
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua")); // 读取脚本
        SECKILL_SCRIPT.setResultType(Long.class); // 返回值
    }

    @PostConstruct
    private void init(){
        es.submit(new voucherOrderHandler());
    }

    private ExecutorService es = Executors.newSingleThreadExecutor();
    private IVoucherOrderService prox ;
    private class voucherOrderHandler implements Runnable{

        @Override
        public void run() {
            while(true){
                try {
                    // 1.获取队列中的订单信息
                    VoucherOrder voucherOrder = blockingQueue.take();
                    // 2.创建订单,用IVoucherOrderService的代理对象，防止事务失效
                    prox.handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }

    @Transactional//防止更新了库存但未保存订单
    public void handleVoucherOrder(VoucherOrder voucherOrder) {
            //更新库存
            seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherOrder.getVoucherId())
                    .update();
            save(voucherOrder);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();

        // 1.执行lua脚本，用redis判断秒杀库存，一人一单，来决定用户是否有资格购买
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int r = result.intValue(); // 转成int
        // 2.判断结果是否为0
        if (r != 0) {
            // 2.1.不为0 ，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        //保存阻塞队列
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        blockingQueue.add(voucherOrder);
        //获取代理对象
        this.prox = (IVoucherOrderService) AopContext.currentProxy();
        // 3.返回订单id
        return Result.ok(orderId);
    }



//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //查询秒杀卷
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now()))
//            return Result.fail("秒杀尚未开始");
//        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now()))
//            return Result.fail("秒杀已经结束");
//        if(seckillVoucher.getStock()<1)
//            return Result.fail("库存不足");
//
//        return createVoucherOrder(voucherId);
//
//    }
//
//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//        //一人一单
//        Long userId = UserHolder.getUser().getId();
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//        //加锁，防止同一用户在同一时间内重复下单
//        if (!lock.tryLock(2000))
//        {
//            return Result.fail("不允许重复下单");
//        }
//        try {
//            Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//            if(count > 0)
//                return Result.fail("用户已经购买过一次");
//
//            //加乐观锁，防止超卖问题
//            //乐观锁认为线程安全问题不一定会发生，因此不加锁，只是在更新数据时去判断有没有其它线程对数据做了修改。如果没有修改则认为是安全的，自己才更新数据。
//            //乐观锁的实现方式有两种
//            //版本控制 检查更新时的 version 是否与查询时的 version 一致
//            //cas 检查更新时的值是否与查询时的值一致
//
//            //TODO 更新库存前还需要检测是否持有锁。否则会造成同一用户重复下单的问题
//            //更新库存
//            boolean success = seckillVoucherService.update()
//                    .setSql("stock=stock-1")
//                    .eq("voucher_id", voucherId)
//    //                .eq("stock",seckillVoucher.getStock())
//                    .gt("stock",0)
//                    .update();
//            if(!success)
//                return Result.fail("库存不足");
//            //插入订单
//            VoucherOrder voucherOrder = new VoucherOrder();
//            voucherOrder.setId(redisIdWorder.nextId("order"));
//            voucherOrder.setUserId(UserHolder.getUser().getId());
//            voucherOrder.setVoucherId(voucherId);
//            save(voucherOrder);
//            return Result.ok(voucherOrder.getId());
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }finally {
//            lock.unlock();
//        }
//    }
}
